cmake_minimum_required(VERSION 3.22.1)
project(grpcapp LANGUAGES C CXX OBJC)

# 设置C++标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 设置iOS平台参数
set(CMAKE_SYSTEM_NAME iOS)
set(CMAKE_OSX_SYSROOT iphoneos)
set(CMAKE_OSX_ARCHITECTURES "arm64")
set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "NO")
set(CMAKE_OSX_DEPLOYMENT_TARGET "14.0" CACHE STRING "Minimum iOS version" FORCE)

# 主项目目录
get_filename_component(MAIN_PROJECT_DIR
    "${CMAKE_CURRENT_SOURCE_DIR}/../../"
    ABSOLUTE)
if(NOT EXISTS "${MAIN_PROJECT_DIR}/CMakeLists.txt")
    message(FATAL_ERROR "主目录CMakeLists.txt不存在: ${MAIN_PROJECT_DIR}")
endif()

# 配置gRPC构建选项
set(BUILD_CLIENT OFF CACHE BOOL "禁用桌面客户端" FORCE)
set(BUILD_SERVER OFF CACHE BOOL "禁用桌面服务端" FORCE)

add_definitions(-DGRPC_DO_NOT_INSTANTIATE_POSIX_POLLER)
# Protobuf和gRPC配置
set(RUN_HAVE_POSIX_REGEX OFF)
set(RUN_HAVE_STEADY_CLOCK OFF)
set(RUN_HAVE_STD_REGEX OFF)
# 无需生成protobuf可执行文件
set(protobuf_BUILD_PROTOC_BINARIES OFF)
set(gRPC_BUILD_CODEGEN OFF)

set(PROTOBUF_BINARY_DIR ${MAIN_PROJECT_DIR}/build/grpc/third_party/protobuf/)
set(GRPC_BINARY_DIR ${MAIN_PROJECT_DIR}/build/grpc/)

# 编译IOS APP，需要MacOS的protoc
set(CMAKE_CROSSCOMPILING ON)

# 添加主项目
add_subdirectory(${MAIN_PROJECT_DIR} ${CMAKE_CURRENT_BINARY_DIR}/main)

# 创建静态库（iOS通常使用静态库）
add_library(IOSServer STATIC
    src/native-lib.cpp
)

# 链接依赖库
target_link_libraries(IOSServer
    server_base
)

# 包含头文件目录
target_include_directories(IOSServer PRIVATE
    ${MAIN_PROJECT_DIR}/src/server/
    src/
)

# 创建iOS应用
add_executable(${PROJECT_NAME} MACOSX_BUNDLE
    app/main.m
    app/AppDelegate.h
    app/AppDelegate.m
    app/ViewController.h
    app/ViewController.m
)

target_link_libraries(${PROJECT_NAME} PRIVATE
    IOSServer
    "-framework UIKit"
    "-framework Foundation"
)

target_include_directories(${PROJECT_NAME} PRIVATE
    ${MAIN_PROJECT_DIR}/src/server/
    src/
    app/
)

set_target_properties(${PROJECT_NAME} PROPERTIES
    MACOSX_BUNDLE TRUE
    MACOSX_BUNDLE_INFO_PLIST "${CMAKE_CURRENT_SOURCE_DIR}/app/Info.plist"
    XCODE_ATTRIBUTE_PRODUCT_BUNDLE_IDENTIFIER "com.example.${PROJECT_NAME}"
    XCODE_ATTRIBUTE_EXECUTABLE_NAME "${PROJECT_NAME}"
    OUTPUT_NAME "${PROJECT_NAME}"
    XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES
)
